﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Web.Caching;

namespace Directory.Web
{
	/// <summary>
	/// WebUtil 的摘要说明
	/// </summary>
	public sealed class WebUtil
	{
		private WebUtil()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}

		public static EventHandler ResetSettingsHandler;

		public static bool IsCurrentUserInRole(string rolename)
		{
			if (!HttpContext.Current.User.Identity.IsAuthenticated)
			{
				return false;
			}
			else if (rolename == "*")
			{
				return false;
			}
			else
			{
				return RoleDataProxy.IsUserInRole(HttpContext.Current.User.Identity.Name, rolename);
			}
		}

		public static bool ValidateUser(string username, string password)
		{
			Directory.BLL.User user = new Directory.BLL.User();
			if (user.ValidateUser(username, password))
			{
				//PerfCounters.IncrementCounter(AppPerfCounter.MEMBER_SUCCESS);
				//System.Web.Management.WebBaseEvent.RaiseSystemEvent(null, 0xfa2, username);
				return true;
			}
			//PerfCounters.IncrementCounter(AppPerfCounter.MEMBER_FAIL);
			//System.Web.Management.WebBaseEvent.RaiseSystemEvent(null, 0xfa6, username);
			return false;
		}

		public static void ResetSettings()
		{
			if (ResetSettingsHandler != null)
			{
				ResetSettingsHandler(null, new EventArgs());
			}
		}

		public static bool TryLogIn(string username, string password, bool IsPersistent)
		{
			//调要bll层，验证用户信息
			if (ValidateUser(username, password))
			{

				//更新cookie
				HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, IsPersistent);
				//FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
				HttpContext.Current.Response.Cookies.Add(authCookie);

				return true;
			}
			return false;
		}

		public static bool IsAdmin(HttpContext context)
		{
			if (!context.User.Identity.IsAuthenticated)
			{
				return false;
			}
			int totalrecords;
			string[] roles = RoleDataProxy.GetRolesForUser(context.User.Identity.Name, 0, 999, out totalrecords);
			foreach (string role in roles)
			{
				if (role != WebSettings.GetInstance().CustomRole && !string.IsNullOrEmpty(role))
				{
					return true;
				}
			}
			return false;
		}

		public static void ClearUserCookie()
		{
			if (HttpContext.Current.Request.Cookies[WebSettings.GetInstance().NickNameCookieKey] != null)
			{
				HttpCookie cookie = new HttpCookie(HttpContext.Current.Server.UrlEncode(HttpContext.Current.User.Identity.Name + "_" + WebSettings.GetInstance().NickNameCookieKey));
				cookie.Expires = DateTime.Now.AddDays(-1);
				HttpContext.Current.Response.Cookies.Add(cookie);
			}
		}
	}
}